﻿using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Linq;
using System.Text;
using Atmk.WaterMeter.MIS.Commons.Interfaces;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Repository;
using Atmk.WaterMeter.MIS.Datas;
using Atmk.WaterMeter.MIS.Entities.Enums;
using Atmk.WaterMeter.MIS.Entities.Models;
using Atmk.WaterMeter.MIS.Services.DataAccess.Base;
using Microsoft.EntityFrameworkCore;

namespace Atmk.WaterMeter.MIS.Services.DataAccess
{
    public class MeterReadingRepository : BaseRepository, IMeterReadingRepository
    {
        private readonly NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 获取水表当前最后的有效读数记录
        /// </summary>
        /// <param name="meterNumber"></param>
        /// <returns></returns>
        //public MeterReadingRecord LastReadingRecord(string meterNumber)
        //{
        //    var record = FindAllAsNoTracking<MeterReadingRecord>().Where(m =>m.Number == meterNumber)
        //        .OrderByDescending(m => m.ReadTime).ToList();
        //    if (!record.Any())
        //        throw new SqlNullValueException();
        //    return record.First();
        //}

        /// <summary>
        ///  获取指定水表列表中，指定接收日期里最新的水表数据
        /// </summary>
        /// <param name="meterNumbers"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public List<MeterReadingRecord> NowDataMeterReadingRecords(List<string> meterNumbers, DateTime date)
        {
            //获取当前日期的水表记录
            var meterRecord = Context.MeterReadingRecord.AsNoTracking()
                .Where(m =>  meterNumbers.Contains(m.CtdeviceId) &&
                            m.ReadTime.Date == date.Date)
                .OrderBy(r => r.CtdeviceId).ThenByDescending(r => r.ReadTime.Date)
                .GroupBy(r => r.CtdeviceId).Select(v => v.First());
            return meterRecord.ToList();
        }

        /// <summary>
        /// 获取指定水表列表中，离指定接收日期里最近的水表数据
        /// </summary>
        /// <param name="meterNumbers"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public List<MeterReadingRecord> LastDateMeterReadingRecords(List<string> meterNumbers, DateTime date)
        {
            //获取当前日期的水表记录
            var meterRecord = Context.MeterReadingRecord.AsNoTracking()
                .Where(m => meterNumbers.Contains(m.CtdeviceId) &&
                            m.ReadTime.Date <= date.Date)
                .OrderBy(r => r.CtdeviceId).ThenByDescending(r => r.ReadTime.Date)
                .GroupBy(r => r.CtdeviceId).Select(v => v.First());
            return meterRecord.ToList();
        }

        /// <summary>
        /// 获取指定范围日期内，最新的各水表的抄表数据
        /// </summary>
        /// <param name="meterNumbers"></param>
        /// <param name="sDate"></param>
        /// <param name="eDate"></param>
        /// <returns></returns>
        public List<MeterReadingRecord> RangeNewDateMeterReadingRecords(List<string> meterNumbers,
            DateTime sDate,
            DateTime eDate)
        {
            var meterRecord = Context.MeterReadingRecord.AsNoTracking()
                .Where(m => meterNumbers.Contains(m.CtdeviceId) &&
                            m.ReadTime.Date >= sDate.Date &&
                            m.ReadTime <= eDate.Date).OrderBy(r => r.CtdeviceId).ThenByDescending(r => r.ReadTime.Date)
                .GroupBy(r => r.CtdeviceId).Select(v => v.First());
            return meterRecord.ToList();
        }

        /// <summary>
        /// 添加水表读数记录
        /// </summary>
        /// <param name="meterNumber">水表编号</param>
        /// <param name="cTime">读取时间</param>
        /// <param name="value">增量</param>
        /// <param name="valveState"></param>
        /// <param name="voltageState">欠压状态</param>
        public bool AddRecorcd(string meterNumber, DateTime cTime, double value, ValveState valveState = ValveState.Opening, int voltageState=0)
        {
            _logger.Info("准备添加水表读数记录");
            try
            {
                var meters = FindAll<MeterReadingRecord>().Where(m =>  m.CtdeviceId == meterNumber)
                    .OrderByDescending(m => m.ReadTime).ToList();
                double last = 0;
                double valuenow = value;
                if (meters.Any())
                {
                    last = meters.First().Value;
                    valuenow = last + value;
                }
                var record = new MeterReadingRecord
                {
                    CtdeviceId = meterNumber,
                    ReadTime = cTime,
                    Value = valuenow,
                    //LastValue = last,
                    ValveState = (int)valveState,
                    Voltage = voltageState.ToString("f2")
                };
                using (var _content=ContextBuilder.Build())
                {
                    _content.MeterReadingRecord.Add(record);
                    var count =_content.SaveChanges();
                    if (count>0)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            catch (Exception e)
            {
                _logger.Error(e);
                throw;
            }
        }

        /// <summary>
        /// 获取指定水表编号范围内的水表读数记录
        /// </summary>
        /// <param name="meterNumbers"></param>
        /// <returns></returns>
        public List<MeterReadingRecord> GetDateMeterReadingRecords(params string[] meterNumbers)
        {
            var meterRecord = Context.MeterReadingRecord.AsNoTracking().Where(m => meterNumbers.Contains(m.CtdeviceId)).ToList();
            return meterRecord;
        }

        /// <summary>
        /// 获取MeterReadingRecord 数据表所有记录
        /// 2019-8-24 马贤辉
        /// </summary>
        public List<MeterReadingRecord> Get_MeterReadingRecord_List()
        {
            var result = Context.MeterReadingRecord.ToList();
            return result;
        }

    }
}